import FYBatchNodeInfo from "./FYBatchNodeInfo";

const { ccclass, property } = cc._decorator;

@ccclass
export default class FYBatch extends cc.Component {
    /** 是否在onLoad里面初始化 */
    @property(cc.Boolean)
    public initOnLoad: boolean = false;
    /** 是否需要同步位置 */
    @property(cc.Boolean)
    public needSyncPos: boolean = false;
    /** 是否需要同步透明度变化 */
    @property(cc.Boolean)
    public needSyncOpacity: boolean = false;
    /** 是否需要同步角度 */
    @property(cc.Boolean)
    public needSyncRotation: boolean = false;
    /** 新的目标对象 */
    @property(cc.Node)
    public newParent: cc.Node = null;
    /** 目标对象的父对象查找次数 */
    @property(cc.Integer)
    public targetParentSearchNum: number = 1;
    /** 需要批处理的目标对象列表 */
    @property(Array(cc.Node))
    public listTarget: Array<cc.Node> = [];
    /** 批处理对象信息列表 */
    private _listFYBatchNodeInfo: Array<FYBatchNodeInfo> = [];


    init() {
        for (let i = 0; i < this.listTarget.length; i++) {
            let info = new FYBatchNodeInfo();
            info.init(i, this.listTarget[i], this.getParent(this.listTarget[i]), this.newParent, this.onBatchNodeDestroy.bind(this), this.needSyncPos, this.needSyncOpacity, this.needSyncRotation);
            // 如果有widget 则关闭
            let widget = this.listTarget[i].getComponent(cc.Widget);
            if (widget) {
                widget.enabled = false;
            }
            this._listFYBatchNodeInfo.push(info);
            info.syncPos();
        }
    }

    /**
     * 获取父对象
     * @param node 目标对象
     */
    getParent(node: cc.Node) {
        if (node === null) {
            return null;
        }
        let nodeParent = node.parent;
        if (nodeParent === null) {
            return null;
        }
        for (let i = 0; i < this.targetParentSearchNum - 1; i++) {
            nodeParent = nodeParent.parent;
            if (nodeParent === null) {
                return null;
            }
        }

        return nodeParent;
    }

    // --------------------- 回调函数 ---------------------- //

    onBatchNodeDestroy(index: number) {
        if (this._listFYBatchNodeInfo && this._listFYBatchNodeInfo[index]) {
            this._listFYBatchNodeInfo[index] = null;
        }
    }

    // --------------------- 生命周期 ---------------------- //

    onLoad() {
        if (this.initOnLoad) {
            this.init();
        }
    }

    onDestroy() {
        for (let i = 0; i < this._listFYBatchNodeInfo.length; i++) {
            if (this._listFYBatchNodeInfo[i]) {
                this._listFYBatchNodeInfo[i].removeMsg();
            }
        }
    }
}
